package code;

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class Test {
	/**
	 * Adapted from code found in j2se 1.5 jdk:
	 *     /src/com/sun/java/swing/plaf/windows/XPStyle 
	 */
	private BufferedImage convert(BufferedImage src, Color color) {
		int w = src.getWidth();
		int h = src.getHeight();
		int type = Transparency.BITMASK;
		BufferedImage dst = getCompatibleImage(w,h,type);
		int rgb;
		if(color != null)
			rgb = color.getRGB() | 0xff000000;
		else
			rgb = 0xffff00ff;
		// Copy pixels a scan line at a time.
		int buf[] = new int[w];
		for(int y = 0; y < h; y++) {
			src.getRGB(0, y, w, 1, buf, 0, w);
			for(int x = 0; x < w; x++) {
				if(buf[x] == rgb)
					buf[x] = 0;
			}
			dst.setRGB(0, y, w, 1, buf, 0, w);
		}
		return dst;
	}

	private JScrollPane getContent() {
		BufferedImage image = getImage();
		Color color = Color.magenta;
		BufferedImage modified = convert(image, color);
		JPanel panel = new JPanel(new GridLayout(1,0,5,0));
		panel.setBackground(Color.LIGHT_GRAY);
		panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		panel.add(new JLabel(new ImageIcon(image)));
		panel.add(new JLabel(new ImageIcon(modified)));
		return new JScrollPane(panel);
	}

	private BufferedImage getImage() {
		int w = 300, h = 300, type = Transparency.OPAQUE;
		BufferedImage image = getCompatibleImage(w,h,type);
		Graphics2D g2 = image.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setPaint(Color.magenta);
		g2.fillRect(0,0,w,h);
		g2.setPaint(Color.blue);
		g2.drawRect(0,0,w-1,h-1);
		g2.setPaint(Color.green.darker());
		g2.fillRect(w/4,h/4,w/2,h/2);
		g2.dispose();
		return image;
	}

	private BufferedImage getCompatibleImage(int w, int h, int type) {
		return GraphicsEnvironment.getLocalGraphicsEnvironment()
		.getDefaultScreenDevice()
		.getDefaultConfiguration()
		.createCompatibleImage(w,h,type);
	}

	public static void main(String[] args) {
		JFrame f = new JFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.add(new Test().getContent());
		f.pack();
		f.setLocation(200,200);
		f.setVisible(true);
	}
}
